Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Oct 16, 2025

Link issues

fixes #6894

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Prevent focus exceptions by replacing Blazor element references with a safe JS interop focus call across input components

Bug Fixes:

  • Prevent null reference exception when focusing input components

Enhancements:

  • Introduce a JavaScript focus helper that safely focuses elements by ID

Chores:

  • Remove direct element references from various input components

Copilot AI review requested due to automatic review settings October 16, 2025 04:56
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 16, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

This PR replaces the ElementReference-based focus logic with a safe JavaScript helper that retrieves elements by ID and focuses them conditionally, removing all @ref bindings and the FocusElement property to prevent focus-related exceptions.

Class diagram for BootstrapInputBase focus logic refactor

classDiagram
    class BootstrapInputBase {
        - string CssClass
        - string ValidCss
        - string PlaceHolder
        - string Type
        - string Id
        - string EventString
        - string CurrentValueAsString
        - string Disabled
        - string ReadonlyString
        - string AdditionalAttributes
        - string ClassName
        - string OnBlur
        - string GetInputId()
        + Task FocusAsync()
        + Task SelectAsync()
    }
    %% Removed property
    %% FocusElement property was removed
    %% FocusAsync method was updated to use JS helper instead of ElementReference
Loading

Flow diagram for new focus logic using JavaScript helper

flowchart TD
    A["Component calls FocusAsync()"] --> B["InvokeVoidAsync('focus', GetInputId())"]
    B --> C["BootstrapInput.razor.js: focus(id)"]
    C --> D["document.getElementById(id)"]
    D --> E{Element found?}
    E -- Yes --> F["el.focus()"]
    E -- No --> G["Do nothing"]
Loading

File-Level Changes

Change Details Files
Introduce safe JS focus helper and update FocusAsync to use it
  • Add focus(id) function in BootstrapInput.razor.js that checks for element existence before calling focus()
  • Change BootstrapInputBase.FocusAsync() to InvokeVoidAsync("focus", GetInputId()) instead of calling FocusElement.FocusAsync()
src/BootstrapBlazor/Components/Input/BootstrapInput.razor.js
src/BootstrapBlazor/Components/Input/BootstrapInputBase.cs
Remove ElementReference property used for focusing
  • Delete protected ElementReference FocusElement declaration from BootstrapInputBase
src/BootstrapBlazor/Components/Input/BootstrapInputBase.cs
Eliminate @ref="FocusElement" bindings across input components
  • Remove @ref attribute from input in BootstrapInput.razor
  • Remove @ref from FloatingLabel.razor input
  • Remove @ref from AutoComplete.razor and AutoFill.razor inputs
  • Remove @ref from BootstrapInputNumber.razor input fragment
  • Remove @ref from Search.razor input
  • Remove @ref from Textarea.razor textarea
src/BootstrapBlazor/Components/Input/BootstrapInput.razor
src/BootstrapBlazor/Components/Input/FloatingLabel.razor
src/BootstrapBlazor/Components/AutoComplete/AutoComplete.razor
src/BootstrapBlazor/Components/AutoFill/AutoFill.razor
src/BootstrapBlazor/Components/InputNumber/BootstrapInputNumber.razor
src/BootstrapBlazor/Components/Search/Search.razor
src/BootstrapBlazor/Components/Textarea/Textarea.razor

Assessment against linked issues

Issue Objective Addressed Explanation
#6894 Prevent focus error when quickly switching between Input and Input Number tabs on the Input documentation page.
#6894 Ensure that focus handling does not trigger exceptions that prevent the page from rendering in Interactive Server mode.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto bot added the bug Something isn't working label Oct 16, 2025
@bb-auto bb-auto bot added this to the 9.11.0 milestone Oct 16, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR prevents focus exceptions in Input components by refactoring the focus mechanism from using ElementReference to JavaScript DOM APIs. The change addresses issue #6894 by removing direct element references that could cause exceptions.

Key changes:

  • Replaced @ref="FocusElement" with JavaScript-based focus implementation
  • Introduced a new focus function in the JavaScript module
  • Updated version to 9.11.3-beta02

Reviewed Changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.

File Description
BootstrapInputBase.cs Removed FocusElement property and updated FocusAsync to use JavaScript
BootstrapInput.razor.js Added new focus function for DOM-based element focusing
Multiple .razor files Removed @ref="FocusElement" from input elements
BootstrapBlazor.csproj Version bump to 9.11.3-beta02

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

export function focus(id) {
const el = document.getElementById(id)
if (el) {
el.focus();
Copy link

Copilot AI Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The focus function should handle cases where the element is not found or cannot be focused. Consider adding error handling or logging when the element doesn't exist or focus fails.

Suggested change
el.focus();
try {
el.focus();
} catch (err) {
console.error(`Failed to focus element with id '${id}':`, err);
}
} else {
console.warn(`Element with id '${id}' not found. Cannot focus.`);

Copilot uses AI. Check for mistakes.
/// </summary>
/// <returns></returns>
public async Task FocusAsync() => await FocusElement.FocusAsync();
public async Task FocusAsync() => await InvokeVoidAsync("focus", GetInputId());
Copy link

Copilot AI Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The FocusAsync method should handle potential JavaScript invocation failures. Consider wrapping in try-catch or returning a result indicating success/failure to maintain the async contract's reliability.

Copilot uses AI. Check for mistakes.
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Components/Input/BootstrapInput.razor.js:3-8` </location>
<code_context>
 import EventHandler from "../../modules/event-handler.js"

+export function focus(id) {
+    const el = document.getElementById(id)
+    if (el) {
+        el.focus();
+    }
+}
+
</code_context>

<issue_to_address>
**suggestion:** The focus function does not handle elements that are not focusable.

Check if the element is focusable before calling el.focus(), or handle potential exceptions to prevent errors.

```suggestion
export function focus(id) {
    const el = document.getElementById(id)
    if (el) {
        // Check if element is focusable
        const isNaturallyFocusable = (
            el instanceof HTMLInputElement ||
            el instanceof HTMLButtonElement ||
            el instanceof HTMLSelectElement ||
            el instanceof HTMLTextAreaElement ||
            (el instanceof HTMLAnchorElement && el.hasAttribute("href"))
        );
        if (isNaturallyFocusable || el.tabIndex >= 0) {
            try {
                el.focus();
            } catch (e) {
                // Optionally log or handle the error
            }
        }
    }
}
```
</issue_to_address>

### Comment 2
<location> `src/BootstrapBlazor/Components/Input/BootstrapInput.razor.js:4` </location>
<code_context>
 import EventHandler from "../../modules/event-handler.js"

+export function focus(id) {
+    const el = document.getElementById(id)
+    if (el) {
+        el.focus();
</code_context>

<issue_to_address>
**issue (bug_risk):** Using getElementById assumes unique IDs across the DOM.

If IDs are not unique, focusing may target the wrong element. Confirm that GetInputId() produces unique IDs for every input.
</issue_to_address>

### Comment 3
<location> `src/BootstrapBlazor/Components/Textarea/Textarea.razor:11` </location>
<code_context>
 }
 <textarea @attributes="AdditionalAttributes" placeholder="@PlaceHolder" id="@Id" class="@ClassName" disabled="@Disabled"
           @bind-value="CurrentValueAsString" @bind-value:event="@EventString" @onblur="@OnBlur"
-          data-bb-shift-enter="@ShiftEnterString" data-bb-scroll="@AutoScrollString" @ref="FocusElement"></textarea>
+          data-bb-shift-enter="@ShiftEnterString" data-bb-scroll="@AutoScrollString"></textarea>
</code_context>

<issue_to_address>
**question:** Textarea loses direct reference, which may affect programmatic focus or selection.

Please ensure the JS-based solution allows programmatic focus and selection of the textarea as reliably as the previous @ref approach.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@ArgoZhang ArgoZhang merged commit 12e71d6 into main Oct 16, 2025
5 checks passed
@ArgoZhang ArgoZhang deleted the feat-focus branch October 16, 2025 04:58
@codecov
Copy link

codecov bot commented Oct 16, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (26cc74a) to head (af195ec).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6920   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          740       740           
  Lines        31847     31811   -36     
  Branches      4468      4468           
=========================================
- Hits         31847     31811   -36     
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(InputBase): prevent Focus error

2 participants